/**
 * 
 */
package common.liusany.admin.service.account;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.liusany.modules.orm.Page;
import com.liusany.modules.orm.PageRequest;
import com.liusany.modules.orm.PropertyFilter;
import common.liusany.admin.dao.account.EmailDao;
import common.liusany.admin.entity.account.Email;

/**
 * @author Administrator
 * 
 */
@Component
@Transactional
public class EmailManager {

	private static Logger logger = LoggerFactory.getLogger(EmailManager.class);

	@Resource
	private DataSource dataSource;
	@Resource
	private EmailDao emailDao;
	@Resource
	private MimeMailService mimeMailService;
	
	private Connection conn = null;

	public Page<Email> findByPage(final PageRequest page,
			final List<PropertyFilter> filters) {
		return emailDao.findPage(page, filters);
	}

	public void deleteAll() {
		emailDao.deleteAll();
	}
	
	public List<Email> getEmailList(int first,int max){
		return emailDao.getList(first, max);
	}
	
	/**
	 * 查询未发送的邮箱
	 * @param max 条数
	 * @return
	 */
	public List<Email> getEmailList(int max){
		return emailDao.getList(max);
	}
	
	
	public void sendEmailFromTxt(File file){
		  try {
				List<String> lines = FileUtils.readLines(file, "UTF-8");
				Integer i = 0;
				
				Long beginTime = System.currentTimeMillis();
				String toMail = "";
				for (String line : lines) {
					if(StringUtils.isNotBlank(line.trim())){
						toMail = line.trim();
						mimeMailService.sendNotificationMail(toMail, "爱状网");
					}
					i++;
				}
				logger.info("发送任务已添加到线程池");
				
				Long endTime = System.currentTimeMillis();
		    	System.out.println("pst+batch："+(endTime-beginTime)/1000+"秒");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	

	public void sendHtmlMail(Email email){
		mimeMailService.sendHtmlMail(email);
	}
	
	/**
	 * 批量修改邮件状态为已发送
	 */
	public  void exeBatchUpdate(){
		
		List<Long> idsList = new LinkedList<Long>(MimeMailService.IDLIST);
		List<Long> fidsList = new LinkedList<Long>(MimeMailService.FIDLIST);
		try {
			 conn = dataSource.getConnection();
			 conn.setAutoCommit(false);
			 PreparedStatement pst = conn.prepareStatement("update acct_email set send_status = ? where id = ?");
			
			 //修改成已发送状态
			 Integer i = 1;
			 for(Long id : idsList){
				 pst.setString(1, "send");
				 pst.setLong(2, id);
				 pst.addBatch();
				 if ((i % 1000 != 0)&&(i==idsList.size())) {
						pst.executeBatch();
						conn.commit();
						pst.clearBatch();
						MimeMailService.IDLIST.removeAll(idsList);
				}
				if (i % 1000 == 0) {
					// 可以设置不同的大小；如50，100，500，1000等等
					pst.executeBatch();
					conn.commit();
					pst.clearBatch();
					MimeMailService.IDLIST.removeAll(idsList);
				}
				i++;
			 }
			 
			//修改成发送失败状态
			Integer j = 1;
			for(Long id : fidsList){
				pst.setString(1, "failed");
				pst.setLong(2, id);
				pst.addBatch();
				if ((j % 1000 != 0)&&(j==fidsList.size())) {
					pst.executeBatch();
					conn.commit();
					pst.clearBatch();
					MimeMailService.IDLIST.removeAll(fidsList);
				}
				if (j % 1000 == 0) {
					pst.executeBatch();
					conn.commit();
					pst.clearBatch();
					MimeMailService.IDLIST.removeAll(fidsList);
				}
				j++;
			}
			 
		} catch (SQLException e) {
			String tempfilePath = new StringBuffer(EmailManager.class.getResource("../../../../../")
	                .getPath()).append(File.separator)
            .append("tempfile")
            .toString();
			File file = new File(tempfilePath+File.separator+"EmailIds.txt");
			try {
				FileUtils.write(file, idsList.toString(), "UTF-8");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	 
	}
	
	/**
	 * 读取数据文件到数据库中
	 * @param file
	 * @return
	 */
	public int fileToDb(File file) {
		int count = 0;//文件中数据总条数
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			conn.setAutoCommit(false);
			Long beginTime = System.currentTimeMillis();
			PreparedStatement pst = conn.prepareStatement("insert into acct_email(id,email,send_status) values (?,?,?)");
			List<String> lines = FileUtils.readLines(file, "UTF-8");
			count = lines.size();
			Integer i = 1;
			for (String line : lines) {
				pst.setInt(1, i);
				pst.setString(2, line);
				pst.setString(3, "unsend");
				pst.addBatch();
				
				
				if ((i % 1000 != 0)&&(i==count)) {
					pst.executeBatch();
					conn.commit();
					pst.clearBatch();
				}
				
				if (i % 1000 == 0) {
					// 可以设置不同的大小；如50，100，500，1000等等
					pst.executeBatch();
					conn.commit();
					pst.clearBatch();
				}
				i++;
			}
			Long endTime = System.currentTimeMillis();
			logger.info("共插入数据"+count+"条,耗时:"+(endTime - beginTime) / 1000	+ "秒");
			pst.close();
			conn.close();
			return count;
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	/**
     * 向文件里写入数据
     * @param filename 文件名
     * @param msg 要写入的内容
     */
    public void createMsgFile(String filename, String msg)
    {
        BufferedWriter bw = null;
        try
        {
            if (!"".equals(filename) && null != filename)
            {
                File file = new File(filename);
                if (!file.exists())
                {
                    boolean flag = file.createNewFile();
                    if (!flag)
                    {
                    	logger.error("", "create new file failed");
                    }
                    bw = new BufferedWriter(new FileWriter(file, true));
                    bw.write(msg);
                    bw.flush();
                }
                else
                {
                    bw = new BufferedWriter(new FileWriter(file, true));
                    bw.newLine();
                    bw.write(msg);
                    bw.flush();
                }
                
            }
        }
        catch (IOException ie)
        {
        	logger.error("SYNC DATA", ie.toString());
        }
        catch (Exception e)
        {
        	logger.error("SYNC DATA", e.toString());
        }
        finally
        {
            try
            {
                if (bw != null)
                {
                    bw.close();
                }
            }
            catch (IOException e)
            {
            	logger.error("SYNC DATA", e.toString());
            }
        }
        
    }
}
